package keter.rabbitmq.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
  发送方同步确认
 */
public class ConfirmSyncSend {

  private static final Logger logger = LoggerFactory.getLogger(ConfirmSyncSend.class);
  private final static String QUEUE_NAME = "hello_confirm";

  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("192.168.1.100");
    //factory.setPort(5672);//default port
    factory.setUsername("haha");
    factory.setPassword("haha");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(
            QUEUE_NAME,           //队列名称
            false,        //是否持久化
            false,       //是否排他
            false,     //不再使用时该队列是否自动删除
            null);

    channel.confirmSelect();

    sendMsg(channel, "Hello World 1!");
    sendMsg(channel, "Hello World 2!");
    sendMsg(channel, "Hello World 3!");
    sendMsg(channel, "Hello World 4!");
    sendMsg(channel, "Hello World 5!");

    channel.close();
    connection.close();
  }

  private static void sendMsg(Channel channel, String message) throws IOException, InterruptedException {
    channel.basicPublish(
            "",   //默认交换器
            QUEUE_NAME,    //路由键：使用“默认”即direct交换器时，QueueName即为ROUTING_KEY
            null,
            message.getBytes("UTF-8")//消息
    );
    System.out.println(" [x] Sent '" + message + "'");
    if(channel.waitForConfirms()) {
      logger.info("[{}]发送成功！",message);
    }
  }
}
